Home |
| Latest | About | Random
# Week 3 Friday Dear Class, Today I'll discuss the `for` loop (**section 8.5**). This is a useful loop pattern for when you know how many times you would want to perform a loop (but it's not limited to this). We will do section 8.4 and more examples next Monday. Then the following Wednesday and Friday we will discuss functions in section 9, but that is not on the exam. I am going to think about what good advice to give you for preparing for the upcoming midterm on **Week 5 Monday**. But right now I would say this: - An old study guide to Midterm 1 is posted on BruinLearn (I am going to look over it again to see if it needs updating, but it seems very applicable). - Make an effort to read sections 2 - 8 of the text. - The text has **review questions** in each section, try them. - Make sure you know how all the syntax, data types, string class, input buffer, control flow that we talked about work. **Make yourself a big list**, **along with examples** that go with them. - Understand what can cause build error, runtime error, or undefined behavior. - Practice look at pieces of code (say in class notes or in the text), and predict what would happen, whether it'd give errors (where and why), and what is the output. Also, **HW3** posted, tentatively due next Friday. You got this!!!!!! -- B. . . . . . . ## Young Gauss. The story goes that young Gauss was impatient and rowdy in class. So his teacher attempted to quiet him down by giving him a math problem. $$ 1 + 2 + 3 + \cdots + 100 = ?? $$"Add the numbers from 1 to 100 all together, and stop bothering the class until you've found the sum!" And when the teacher was just about to sit down and relax, Gauss shouted, "It's ----"! Well, imagine if Gauss had the power of the **loop**... Write a `while` loop that calculates this. We will then learn another loop called `for` loop. . . . . . ## `for` loop. A `for` loop is useful to repeat an action for a known certain amount of times. Below this `for` loop prints out the `int`s from `0` to `9`: ```cpp #include using namespace std; int main() { for (int i = 0; i < 10; ++i) { cout << i << endl; } return 0; } ``` ![[1-teaching/ucla-2026-fall-pic-10a/---files/for.svg]] In general the format of a `for` loop looks like this: ```cpp for (init-statement; condition; expression){ statements; } ``` - Note two `;` separating three parts in the `( )` for `for`. - All three parts `init-statement; condition; expression` are optional and can be empty. - When all three parts are empty, we get infinite loop. - The variables from the `init-statement` are in scope for the whole loop, including the condition, the expression, and the body. - Variables declared in the body exist only inside the body, for one iteration at a time. - Once the loop ends, all variables *declared*, including ones *declared* in `init-statement` go out of scope and are destroyed. - `break` can also break out of `for` loops. - There is also `continue` keyword. - In a `for` loop: Skip directly to the `expression` and go back to checking the `condition`. - In a `while` loops: Skip the rest of the loop body and go back to the checking the condition. . . . . A `for` loop is **nearly** the same as the following: ```cpp { init-statement; while (condition) { statements; expression; } } ``` **A technical detail that it's ok to just roughly be aware.** Except the fact that the `condition` in `while` loop cannot be empty, and that here in this `while` loop the `init-statement` is in an outer scope than the `while` loop body (so you can declare a variable with the same name as you did in `init-statement`. But why would you do such strange thing you have to be careful). . . . . . **Examples. Young Gauss.** Let us write a function by adding up all consecutive integers from `a` to `b` (inclusively), where `a < b`. ```cpp #include using namespace std; int main() { int a = 3, b = 20, current_sum = 0; for (int i = a; i <= b; i++) { current_sum += i; } cout << current_sum; } ``` Can you modify it to add up all the **perfect squares**, from $a^{2}$ to $b^{2}$? **Example. Factorial.** Let us find $a!$, $a$ factorial. For example, $5! = 5 \cdot 4\cdot 3 \cdot 2\cdot 1 = 120$. ```cpp #include using namespace std; int main() { int a = 5; int current_product = 1; for (int i = a; i >= 1; --i) { current_product *= i; } cout << current_product; } ``` **Example. A mysterious product of infinitely many fraction.** Start with the fraction $\frac{2}{1}$. Then multiply to it $\frac{2}{3}$, then $\frac{4}{3}$, then $\frac{4}{5}$. then $\frac{6}{5}$, ... The pattern looks like this: ![[1-teaching/ucla-2026-fall-pic-10a/---files/wallis.svg]] Write a function to see what this might converge to, by multiplying a large enough number of terms together! ```cpp #include using namespace std; int main() { double numer = 2; double denom = 1; double current_product = numer / denom; // 100 terms seems a lot, try more later for (int i = 0 ; i < 100 ; ++i) { // USE THE ODD OR EVEN-NESS OF i // TO DETERMINE HOW TO MODIFY THE NEXT numer AND denom // MULTIPLY THEM TO current_product } return 0; } ``` . . . . . . **Remark.** It is usual to count out `N` things by going `1, 2, 3, ..., N`. But in computer science, especially in a 0-index language like C++, it is often to count out `N` things by going `0, 1, 2, ..., N-1`. So to repeat a loop `N` times, a common pattern is to do ```cpp for(int i = 0 ; i < N; i++) { ... } ``` But a `for` loop doesn't always look like this, AND ones that do look like that need not do a loop `N` times either! **Example 1.** Predict what does this do. ```cpp #include using namespace std; int main() { for (int i = 0; i < 10; i += 2) { cout << i; } return 0; } ``` What if we change `+= 2` to `*= 2`? **Example 2.** Predict what does this do. ```cpp #include using namespace std; int main() { for (int i = 0; i < 10; ++i) { cout << i; if (i < 5) { i *= 2;} if (i > 5) { i -= 1;} } return 0; } ``` What if we change the `2` to `3`? Or to `4`? **Example 3.** Let us write a program that turns a user input word that is all lower case into all upper case. Note, when referring to indexing or describing sizes of containers, what's the appropriate data type? ```cpp #include #include using namespace std; int main() { string input; cout << "Enter a single word that is in all lower case\n"; cin >> input; size_t N = input.length(); for (size_t i = 0; i < N; i++) { input[i] += 'A' - 'a'; } } ``` --- **Check out the following in your own time for more practice and exploration!** ## Sieve of Eratosthenes. [Eratosthenes](https://en.wikipedia.org/wiki/Eratosthenes) lived around 276 BC to 195 BC, and he was one smart cookie. Among his great achievements ([[1-teaching/summer program 2023/week 1/Cosmic_distance_ladder|estimating the radius of Earth]], the axial tilt of Earth, dating the events of the Trojan war at around 1000 BC, being the chief librarian of the Library of Alexandria...) he came up with an efficient way to find **prime numbers** (positive integers with exactly two divisors) called **the sieve of Eratosthenes**. It goes like this: - Say you want to find all prime numbers $\le N$. Write down the numbers 1, 2, 3, ...., N. - Cross 1 out, as 1 is not a prime. - Now, for the next number that is not crossed out, say $p$, box it, it is a **prime**. Then cross out every multiple of this number you just circled (except $p$ itself), starting at $p^{2}$. That is, cross out $p^{2},(p+1)p,(p+2)p,...$ and so on, up to your chosen $N$. - Repeat to the next number that is not yet crossed out. For example, if $N = 10$, it goes like this. - Cross out 1. - Box 2, a prime. Cross out 4, 6, 8, 10. - Box 3, a prime. Cross out 9. - Box 5, a prime. Cross out 10. - Box 7, a prime. - We left with this $\cancel1, \fbox{2}, \fbox{3}, \cancel4, \fbox{5}, \cancel6, \fbox{7}, \cancel8, \cancel9, \cancel{10}$ Cool! We have four prime numbers less than equal to 10. Hmm... - How many prime numbers are there less than equal to 100? - How about less equal to 1000? or 1000000? Let's write some C++ to find out! (Though there are faster ways to list primes, the sieve is one of the top shelf methods!) - To keep track of which number is a prime or not, we can create a giant string of length `N+1` characters, say all `t`'s. And we use its position `i` to keep track whether the integer `i` is a prime or not. If `i` is a prime, keep index `i` character as `t`, otherwise make it `f`. - Later, we will see another data type that is suitable to store a *list* of things by using the `vector` class! [[1-teaching/ucla-2026-fall-pic-10a/sieve-answer|suggested answer to Eratosthenes sieve]] ## Draw shapes. **Draw a square.** Write a program that asks for a user input of size `int n` that is 2 or more, and print out a square made of `'*'` characters along its border. For example, if `n = 4`, then ```cmd Enter size of square: 4 **** * * * * **** ``` **Draw a circle.** Write a program that asks for a user input of size `int n` that is 2 or more, and it gives a filled circle made of `'*'` characters. For example, ```cmd Enter size of circle: 10 ***** ******* ********* ********* ********* ********* ********* ******* ***** ``` **Note.** Since the console usually prints more tall than wide, you can print `* ` and ` ` with an extra space to make it wider. [[1-teaching/ucla-2026-fall-pic-10a/drawing-answers|suggested drawing answers]] ## A good challenge: Number of anagrams. Given a word, any unique rearrangement of the word is an **anagram** of the word (the anagram itself does not have to be a real word). For example, `bee` has a total of 3 anagrams ``` bee ebe eeb ``` And the word `polo` has a total of 12 anagrams ``` polo pool ploo oplo opol oolp oopl loop lopo lpoo olpo olop ``` If we only want the *number* of such anagrams, then there's a nice formula, it is $$ \frac{\ell!}{f_{1}! f_{2}! f_{3}! \cdots f_{k}!} $$ where $\ell$ is the total number of letters while $f_{i}$ is the frequency of each unique letter. For example, `bee` of length `3`, ``` unique letter frequency b 1 e 2 ``` has a total of $\frac{3!}{1!2!} = 3$ anagrams. While `polo` of length `4`, ``` unique letter freuqnecy p 1 o 2 l 1 ``` has a total of $\frac{4!}{1!2!1!} =12$ anagrams. And `mississippi` has length `11`, ``` unique letter freuqnecy m 1 i 4 s 4 p 2 ``` has a total of $\frac{11!}{1!4!4!2!} = 34650$ anagrams. Write a piece of code to take user input word and find the number of anagram it has. [[1-teaching/ucla-2026-fall-pic-10a/anagrams-answer|suggested answer to anagrams]]